<template>
  <view class="container">
    <!-- 搜索栏和热量记录并排显示 -->
    <view class="search-and-title">
      <view class="title">
        <text>热量\n记录</text>
      </view>
      <view class="search-bar">
        <input class="search-input" placeholder="请输入食物名称" v-model="searchQuery" />
        <button class="search-btn" @click="onSearch">搜索</button>
      </view>
    </view>

    <!-- 热量信息卡片 -->
    <view class="calorie-card">
      <!-- 日期选择器 -->
      <picker mode="date" @change="onDateChange">
        <view class="date-picker">{{ date }}</view>
      </picker>

      <!-- 仪表盘 -->
      <view class="charts-box">
        <qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
      </view>

      <!-- 热量信息 -->
      <view class="calorie-info">
        <text class="calorie-title">热量统计</text>
        <view class="calorie-row">
          <text>总摄入：</text>
          <text class="highlight">{{ totalIntake }}</text>/<text>{{ targetIntake }}</text> 千卡
        </view>
      </view>

      <!-- 营养信息 -->
      <view class="nutrition-info">
        <text class="nutrition-title">营养成分</text>
        <view class="nutrition-row">
          <view class="nutrient">
            <text>蛋白质：</text>
            <text class="highlight">{{ protein }} 克</text>
          </view>
          <view class="nutrient">
            <text>脂肪：</text>
            <text class="highlight">{{ fat }} 克</text>
          </view>
          <view class="nutrient">
            <text>碳水化合物：</text>
            <text class="highlight">{{ carbs }} 克</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 饮食日记模块 -->
    <view class="meal-diary">
      <text class="meal-diary-title">饮食日记</text>

      <!-- 饮食日志 -->
      <view class="meal-log">
        <view class="meal-item" v-for="meal in meals" :key="meal.name">
          <view class="meal-content">
            <image class="meal-icon" :src="getMealIcon(meal.name)" />
            <text class="meal-name">{{ meal.name }}</text>
          </view>
          <button class="add-btn" @click="addFood(meal.name)">+</button>
        </view>
      </view>
    </view>

    <view class="meal-records">
      <!-- 遍历餐食记录 -->
      <view class="meal-card" v-for="record in mealRecords" :key="record.id">
        <view class="meal-card-header">
          <text :class="`meal-type ${record.meal_type}`">{{ record.meal_type }}</text>
          <text class="food-name">{{ record.food_name }}</text>
        </view>
        <view class="meal-card-body">
          <view class="meal-info">
            <text>摄入量:</text>
            <text class="info-value">{{ record.weight }} 克</text>
          </view>
          <view class="meal-info">
            <text>热量:</text>
            <text class="info-value">{{ record.calories }} 千卡</text>
          </view>
          <view class="meal-info">
            <text>蛋白质:</text>
            <text class="info-value">{{ record.protein }} 克</text>
          </view>
          <view class="meal-info">
            <text>脂肪:</text>
            <text class="info-value">{{ record.fat }} 克</text>
          </view>
          <view class="meal-info">
            <text>碳水化合物:</text>
            <text class="info-value">{{ record.carbs }} 克</text>
          </view>
        </view>
      </view>

      <!-- 无记录提示 -->
      <view v-if="mealRecords.length === 0" class="no-records">
        <text>暂无进食记录</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '', // 搜索输入
      date: '', // 当前日期
      totalIntake: 0, // 总摄入热量
      protein: 0,
      fat: 0,
      carbs: 0,
      targetIntake: 1500, // 目标摄入
      chartData: {}, // 仪表盘数据
      loading: false, // 是否加载中
      mealRecords: [], // 存储当天进食记录
      opts: {
        color: ["#4CAF50", "#FFC107", "#FF5722", "#00BCD4", "#FF9800", "#2196F3", "#E91E63", "#9C27B0", "#8BC34A"],  // 更柔和的颜色
        padding: undefined,
        title: {
          name: "总摄入热量",
          fontSize: 18,  // 调整标题字体大小
          color: "#333333",  // 更深的颜色，增加可读性
          offsetY: 10
        },
        subtitle: {
          name: "目标摄入热量",
          fontSize: 14,  // 副标题的字体较小
          color: "#666666",  // 更浅的颜色
          offsetY: 10
        },
        extra: {
          gauge: {
            type: "progress",
            width: 18,  // 缩小进度条宽度，使其更精致
            labelColor: "#333333",  // 文字颜色加深
            startAngle: 0.75,
            endAngle: 0.25,
            startNumber: 0,
            endNumber: 100,
            labelFormat: "{value}%",  // 格式化标签，显示百分比
            splitLine: {
              fixRadius: -8,
              splitNumber: 10,
              width: 10,  // 调整分割线的宽度
              color: "#DDDDDD",  // 更浅的颜色
              childNumber: 5,
              childWidth: 6  // 子分割线的宽度
            },
            pointer: {
              width: 24,  // 调整指针宽度
              color: "#FF5722",  // 更醒目的指针颜色
              borderWidth: 2,  // 给指针添加边框
              borderColor: "#FF5722",  // 指针边框颜色
              shape: "triangle"  // 使用三角形指针
            }
          }
        }
      },
      meals: [
        { name: '早餐', foods: [] },
        { name: '午餐', foods: [] },
        { name: '晚餐', foods: [] },
        { name: '加餐', foods: [] }
      ]
    };
  },
  onPullDownRefresh() {
    this.refreshRecords(); // 下拉刷新时重新加载记录
  },
  methods: {
    // 获取固定的用餐图标
    getMealIcon(mealName) {
      const icons = {
        早餐: require('@/static/meals/breakfast.svg'),
        午餐: require('@/static/meals/lunch.svg'),
        晚餐: require('@/static/meals/dinner.svg'),
        加餐: require('@/static/meals/snack.svg')
      };
      return icons[mealName];
    },

	async initPage() {
      // 使用组件中的响应式 date 属性
      if (!this.date) {
        const today = new Date();
        this.date = today.toISOString().split('T')[0]; // 设置当前日期
      }

      const userData = await this.fetchUserData();
      console.log("userData: ", userData);

      this.totalIntake = userData.totalIntake || 0;
      this.targetIntake = userData.targetIntake || 0;
      this.protein = (userData.protein || 0).toFixed(1);
      this.fat = (userData.fat || 0).toFixed(1);
      this.carbs = (userData.carbs || 0).toFixed(1);

      this.initGauge(); // 初始化仪表盘
      this.fetchMealRecords();
    },

    // 获取用户热量统计数据
    async fetchUserData() {
      try {
        const response = await uni.request({
          url: `${this.$baseUrl}/calorie/calorieInfo`,
          method: 'GET',
          header: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token')
          },
          data: { date: this.date }
        });

        if (response[1].statusCode === 200) {
          return response[1].data;
        } else {
          throw new Error('获取用户热量统计失败');
        }
      } catch (error) {
        console.error(error.message);
        return { totalIntake: 0, targetIntake: 0 };
      }
    },

    // 获取用餐记录
    async fetchMeals() {
      try {
        const response = await uni.request({
          url: `${this.$baseUrl}/calorie/mealsInfo`,
          method: 'GET',
          header: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token')
          },
          data: { date: this.date }
        });

        if (response[1].statusCode === 200) {
          return response[1].data;
        } else {
          throw new Error('获取用餐记录失败');
        }
      } catch (error) {
        console.error(error.message);
        return [];
      }
    },

    initGauge() {
      // 计算 progress
      let progress = 0;
      if (this.targetIntake > 0) {
        progress = (this.totalIntake / this.targetIntake); // 计算百分比
      }

      // 确保 progress 是有效的，不为 NaN 或小于 0
      if (isNaN(progress) || progress < 0) {
        console.error("Invalid progress value:", progress);
        progress = 0;  // 设置为 0 确保不会出现异常
      }

      // 设置 chartData
      this.chartData = {
        categories: [
          { value: 0.2, color: "#1890ff" },
          { value: 0.8, color: "#2fc25b" },
          { value: 1, color: "#f04864" }
        ],
        series: [
          {
            name: "完成率",
            data: progress,
          }
        ]
      };

      // 确保 chartData 和 data 数组存在且有效
      if (this.chartData && this.chartData.series && this.chartData.series[0].data) {
        console.log('Calculated Progress:', progress);
        console.log('Chart Data:', this.chartData);
      } else {
        console.error('Error: Invalid chartData or series[0].data');
      }
    },

    async addFood(mealType) {
      try {
        // 使用 uni.navigateTo 跳转，并传递 mealType 参数
        uni.navigateTo({
          url: `/pages/index/foodRecord?mealType=${mealType}`, // 将 mealType 作为查询参数传递
        });
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    },

    // 获取当天的进食记录
    // 获取餐食记录
    async fetchMealRecords() {
      try {
        const token = uni.getStorageSync('access_token');
        if (!token) {
          console.error('用户未登录，请先登录');
          uni.showToast({ title: '请先登录', icon: 'none' });
          return;
        }

        const response = await uni.request({
          url: `${this.$baseUrl}/calorie/getMealRecords`, // 假设对应的后端接口路径
          method: 'GET',
          header: {
            Authorization: `Bearer ${token}`, // 使用存储的 access_token
          },
          data: { date: this.date }, // 提供查询日期参数
        });

        const [error, result] = response;

        if (result.statusCode === 200 && result.data && result.data.meals) {
          // 格式化并更新餐食记录数据
          const formattedRecords = Object.entries(result.data.meals).flatMap(([mealType, records]) => {
            return records.map(record => ({
              ...record,
              meal_type: mealType, // 添加餐次类型
            }));
          });

          this.mealRecords = formattedRecords;
        } else {
          console.error('获取进食记录失败', result.data);
          uni.showToast({
            title: result.data.detail || '获取进食记录失败',
            icon: 'none',
          });
        }
      } catch (error) {
        console.error('获取进食记录失败:', error.message);
        uni.showToast({
          title: '获取进食记录失败，请稍后重试',
          icon: 'none',
        });
      } finally {
        this.loading = false; // 关闭加载状态
        uni.stopPullDownRefresh(); // 停止下拉刷新动画
      }
    },
	async onReady() {
	  await this.initPage();
	},
	// 刷新记录
	refreshRecords() {
	  this.mealRecords = []; // 清空已有记录
	  this.initPage();
	},
	onShow() {
	  this.initPage();
	},
	onDateChange(e) {
	      // 更新日期并刷新记录
	  this.date = e.detail.value;
	  this.refreshRecords();
	  this.initPage();
	},
  },
};
</script>

<style>
.search-and-title {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
  /* 减小间距 */
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin-right: 20px;
  /* 适当减少右侧间距 */
}

.container {
  padding: 20px;
  background-color: #F2F6F4;
  color: #333333;
  font-family: 'Arial', sans-serif;
}

.search-bar {
  height: 40px;
  display: flex;
  flex: 1;
  align-items: center;
  padding: 12px;
  background: #D0E6D7;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  background: transparent;
  border: none;
  color: #4D5B5B;
  padding: 8px 12px;
  font-size: 18px;
  border-radius: 10px;
}

.search-btn {
  display: flex;
  /* 使用flex布局 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  height: 50px;
  width: 50px;
  /* 设置固定宽度，确保按钮大小 */
  background: #A7C6A6;
  border: none;
  font-size: 17px;
  color: #fff;
  padding: 0;
  /* 去除内边距 */
  border-radius: 10px;
  margin-left: 12px;
  cursor: pointer;
}

.search-btn:hover {
  background: #8DAF8E;
}

.calorie-card {
  padding: 20rpx;
  background-color: rgba(16, 128, 64, 0.12);
  border-radius: 16rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
  margin-left: 10px;
  margin-right: 10px;
}

/* 日期选择器样式 */
.date-picker {
  text-align: center;
  font-size: 34rpx;
  /* 增大字体 */
  color: #4A4A4A;
  /* 改为深灰色，更加柔和 */
  padding: 18rpx 0;
  /* 增加上下内边距 */
  margin-bottom: 24rpx;
  /* 增加下边距，避免和其他元素太挤 */
  background: linear-gradient(135deg, #F4F4F4, #E0E0E0);
  /* 渐变背景 */
  border-radius: 12rpx;
  /* 增加圆角效果 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  /* 添加轻微阴影 */
  transition: all 0.3s ease;
  /* 添加过渡效果 */
}

/* 鼠标点击时的交互效果 */
.date-picker:active {
  transform: scale(0.98);
  /* 点击时轻微缩小 */
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
  /* 增加点击时的阴影 */
}

.date-picker:hover {
  background-color: #e6e6e6;
  /* 鼠标悬停时的颜色变化 */
}

.charts-box {
  margin-bottom: 30rpx;
  text-align: center;
}

.calorie-info,
.nutrition-info {
  margin-top: 20rpx;
  padding: 16rpx;
  border: 1rpx solid #eaeaea;
  border-radius: 12rpx;
  background-color: #fafafa;
}

.calorie-title,
.nutrition-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 12rpx;
}

.calorie-row,
.nutrition-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.nutrient {
  text-align: center;
}

.highlight {
  font-size: 28rpx;
  color: #ff5722;
  font-weight: bold;
}

.meal-log {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-top: 20px;
}

/* 饮食日记模块背景色 */
.meal-diary {
  background-color: #f4f8f7;
  /* 更柔和的背景色 */
  padding: 5px;
  margin-top: 10px;
  border-radius: 15px;
  margin-bottom: 20px;
}

.meal-diary-title {
  font-size: 22px;
  /* 稍微增大字体 */
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 10px;
  text-align: center;
}

/* 餐食项样式 */
.meal-item {
  text-align: center;
  background: #E3F9E5;
  /* 更清新的绿色背景 */
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.meal-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.meal-icon {
  width: 40px;
  height: 35px;
}

.meal-name {
  font-size: 17px;
  /* margin-top: 5px; */
  color: #4D5B5B;
  font-weight: 600;
}

.add-btn {
  margin-top: 4px;
  background: linear-gradient(135deg, #8DAF8E, #A7C6A6);
  /* 渐变背景 */
  color: #fff;
  border: none;
  border-radius: 12px;
  /* 增加圆角 */
  padding: 8px 12px;
  /* 调整内边距 */
  font-size: 36px;
  /* 更大字号 */
  width: 48px;
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s ease;
}

.add-btn:hover {
  background: linear-gradient(135deg, #A7C6A6, #8DAF8E);
  /* 鼠标悬停渐变 */
}

/* 卡片样式 */
.meal-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 18px;
  padding: 18px;
  transition: transform 0.3s ease;
  /* 添加卡片过渡动画 */
}

.meal-card:hover {
  transform: translateY(-4px);
  /* 卡片悬浮效果 */
}

.meal-card-header {
  display: flex;
  justify-content: space-between;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 12px;
  margin-bottom: 14px;
}

.meal-type {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.food-name {
  font-size: 18px;
  color: #374151;
  font-weight: 600;
}

.meal-card-body {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.meal-info {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  color: #6c757d;
}

/* 数值高亮 */
.info-value {
  font-weight: bold;
  color: #111827;
}

.no-records {
  text-align: center;
  color: #9ca3af;
  font-size: 18px;
  margin-top: 30px;
}

/* 每餐类型颜色 */
.meal-type.早餐 {
  color: #f59e0b;
  /* 橙色 */
}

.meal-type.午餐 {
  color: #10b981;
  /* 绿色 */
}

.meal-type.晚餐 {
  color: #3b82f6;
  /* 蓝色 */
}
</style>